#include "stdafx.h"
#include "CharacterVM.h"
#include "moc_CharacterVM.cpp"
#include <QtCore/QMetaProperty>
#include <QtXml/QDomDocument>
#include <QtCore/QFile>

#define CHARACTER_DOC_ROOT "PalladiumCharacterGenerator"

#pragma region Constructor

CharacterVM::CharacterVM():
	_PrimarySkills(&_model.PrimarySkills()),
	_SecondarySkills(&_model.SecondarySkills()),
	_ExtraordinaryAbilities(&_model.ExtraordinaryAbilities()),
	_WeaponProficiencies(&_model.WeaponProficiencies()),
	_Equipment(&_model.Equipment())
{
}

CharacterVM::~CharacterVM(void)
{
}

#pragma endregion

#pragma region Public Methods and Operators

bool CharacterVM::Serialize(const QString& fileName)
{
	QDomDocument doc(CHARACTER_DOC_ROOT);

	QDomElement root = doc.createElement("PalladiumCharacterGenerator");
	doc.appendChild(root);

	QDomElement model = doc.createElement("Character");
	root.appendChild(model);

	_model.Serialize(&doc, &model);

	QFile file(fileName);
	if (file.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text))
	{
		file.write(doc.toString().toUtf8());

		file.close();
	}

	return false;
}

bool CharacterVM::Deserialize(const QString& fileName)
{
	QDomDocument doc(CHARACTER_DOC_ROOT);
	QFile file(fileName);
	if (file.open(QIODevice::ReadOnly))
	{
		if (doc.setContent(&file)) 
		{
			QDomElement tag = doc.firstChildElement("PalladiumCharacterGenerator");
			if (!tag.isNull())
			{
				QDomElement model = tag.firstChildElement("Character");

				if (!model.isNull())
					return _model.Deserialize(&doc, &model);
			}
		}

		file.close();
	}
	
	return false;
}

void CharacterVM::CopyDataFrom(const CharacterVM& source)
{
	const QMetaObject *metaobject = source.metaObject();
	int count = metaobject->propertyCount();
	for (int i=0; i<count; ++i) 
	{
		QMetaProperty metaproperty = metaobject->property(i);
		const char *name = metaproperty.name();

		if (metaproperty.isStored(&source))
		{
			setProperty(name, source.property(name));
		}
	}

	setImage(source.ImageAsBytes());

	CopyListDataFrom(PrimarySkills(), source.PrimarySkills());
	CopyListDataFrom(SecondarySkills(), source.SecondarySkills());
	CopyListDataFrom(ExtraordinaryAbilities(), source.ExtraordinaryAbilities());
	CopyListDataFrom(WeaponProficiencies(), source.WeaponProficiencies());
	CopyListDataFrom(Equipment(), source.Equipment());
}

void CharacterVM::CopyListDataFrom(QAbstractTableModel& target, const QAbstractTableModel& source)
{
	target.removeRows(0, target.rowCount());

	// Go to rowCount() - 1 because the VM's have a fake row at the end
	for (int row = 0; row < source.rowCount() - 1; row++) 
	{
		for (int col = 0; col < source.columnCount(); col++)
		{
			target.setData(target.index(row, col), source.data(source.index(row, col)));
		}
	}

	target.layoutChanged();
}

#pragma endregion

#pragma region Helper Methods

#pragma endregion

